// coaches-detail.js
var app = getApp()
var req = require('../../utils/reqUtils.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    startTime:[
    ],
    endTime: ["请先选择起始时间"],
    selstartTime:"请选择",
    selendTime:"请选择",
    date : [],
    activedateid : 0,
    modalContent: "",
    courseId:0,
    modalHidden: true,
    startY:0,
    timedateid:0,
    course:[],
    start_date:'',
    end_date:'',
    strat_time:'',
    end_time:'',
    selectDay:'',
    selectStartTime:'',
    selectEndTime:'',
    class_id:0,
    duration:''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const that = this;
    console.log('onLoad');
    const coachId = options.id;
    req.post('/coachDetails/index', {id:options.id}, 1).then(res => {
      console.log(res.data);
      req.post('/get_class_info/index', {'coach_id':res.data.coachDetails.coach_id,'course_id':res.data.coachDetails.course[0].course_id}, 1).then(resC => { 
        console.log(1); 
        that.setData({
          start_date:resC.data.class_info[0].start_date,
          end_date:resC.data.class_info[0].end_date,
          start_time:resC.data.class_info[0].start_time,
          end_time:resC.data.class_info[0].end_time,
          duration:resC.data.class_info[0].duration
        })
        var date = [{id:-1,'datestr':'时间日期','state':1}];
        for(var i = 0;i<7;i++){
          var onedate = {};
          onedate.id = i;
          onedate.datestr = that.setTime(i,resC.data.class_info[0].start_date);
          date.push(onedate);
        }
        var starttimedatetime = (resC.data.class_info[0].start_time).split(':');
        var endtimedatetime = (resC.data.class_info[0].end_time).split(':');
        var hours = 0;
        var startTime = [];
        var broken = parseInt(((parseInt(endtimedatetime[0]) - parseInt(starttimedatetime[0]))*60)/resC.data.class_info[0].duration)
        for(var i = 0;i<=broken;i++){
          var hoursDate = parseInt((resC.data.class_info[0].duration*i)/60);
          var minutesDate = (resC.data.class_info[0].duration*i) - 60*hoursDate;
          hours = parseInt(starttimedatetime[0])+hoursDate;
          startTime[i] = (hours < 10 ? ('0' + hours) : hours)+':'+(minutesDate < 10 ? ('0' + minutesDate) : minutesDate);
        }
        that.setData({
          date:date,
          startTime: startTime, 
          class_id:resC.data.class_info[0].class_id
        })         
        console.log(resC.data.class_info[0]['appointment_time']);
        let appointment_time = resC.data.class_info[0]['appointment_time'];
        var idStr = [];
        for(var i = 0;i<appointment_time.length;i++){
          let Month = new Date(appointment_time[i]['start_date']).getMonth()+1;
          let Day = new Date(appointment_time[i]['start_date']).getDate();
          let time = (Month < 10 ? ('0' + Month) : Month)+'-'+(Day < 10 ? ('0' + Day) : Day);
          let hours = new Date(appointment_time[i]['start_date']).getHours();
          let minutesDate = new Date(appointment_time[i]['start_date']).getMinutes();
          let times = (hours < 10 ? ('0' + hours) : hours)+':'+(minutesDate < 10 ? ('0' + minutesDate) : minutesDate);
          let str_d = '';
          let str_t = '';
          for(var ii = 0;ii<date.length;ii++){
            if(date[ii].datestr == time){
              str_d = ii-1
            }
            if(startTime[ii] == times){
              str_t = ii
            }
          }
          
          idStr[i] = str_t+'-'+str_d;
            // console.log(new Date(appointment_time[i]['start_date']).getHours());
            // console.log(new Date(appointment_time[i]['start_date']).getMinutes());
        }
        that.setData({
          idStr:idStr
        })  
        console.log(idStr); 
        idStr.forEach(function(itme,index){
          date.forEach(function(itme1,index1){
            if(itme == itme1.datestr){
              // console.log('***');  
            }else{
              // console.log(itme+'_'+itme1.datestr);
            }
          })

          // console.log(itme);
        })
        // console.log(idStr);
      })

      
        this.setData({  
          // coach:res.data.coachDetails,
          course:res.data.coachDetails.course
        })
    });
    console.log(options.id); 

    var date = [{id:-1,'datestr':'时间日期'}];
    for(var i = 0;i<7;i++){
      var onedate = {};
      onedate.id = i;
      onedate.datestr = that.fun_date(i);
      date.push(onedate);
    }
    var datetime = new Date();
    const hours = datetime.getHours();
    const minutes = datetime.getMinutes(); 
    const curtime = (hours < 10 ? ('0' + hours) : hours) + ":" + (minutes < 10 ? ('0' + minutes) : minutes);
    var startTime = that.data.startTime;
    // startTime = this.getTimeArray(startTime, curtime);
    console.log(startTime);
    that.setData({
      date:date,
      startTime: startTime
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  },
  initendTimeData: function (startTime) {

  },
  bindPickerstartTimeChange: function (event) {
    var selIterm = this.data.startTime[event.detail.value];
    if (selIterm === "今天无有效时间") {
      return;
    }
    var endTime = this.data.startTime;
    endTime = this.getTimeArray(endTime, selIterm);
    this.setData({
      selstartTime: selIterm,
      endTime: endTime
    })
    // this.initCityData(2, selIterm)
  },
  bindPickerendTimeChange: function (event) {
    var selIterm = this.data.endTime[event.detail.value];
    if (selIterm === "请先选择起始时间" || selIterm === "今天无有效时间"){
      return;
    }
    this.setData({
      selendTime: selIterm,
    })
  },
  tabClick: function (e) {
    var d = new Date();
    var mon = d.getMonth() + 1;
    var day = d.getDate();
    const curtime = (mon < 10 ? ('0' + mon) : mon) + "-" + (day < 10 ? ('0' + day) : day);
    var startTime = [
      "09:00", "09:30", "10:00", "10:30", "11:00", "11:30",
      "12:00", "12:30", "13:00", "13:30", "14:00", "14:30",
      "15:00", "15:30", "16:00", "16:30", "17:00", "17:30",
      "18:00", "18:30", "19:00", "19:30", "20:00", "20:30",
      "21:00", "21:30", "22:00"
    ];
    console.log(e.currentTarget.id);
    // if (this.data.date[e.currentTarget.id].datestr.indexOf(curtime) >= 0){
    //   var datetime = new Date();
    //   const hours = datetime.getHours();
    //   const minutes = datetime.getMinutes();
    //   const curtime = (hours < 10 ? ('0' + hours) : hours) + ":" + (minutes < 10 ? ('0' + minutes) : minutes);
    //   startTime = this.getTimeArray(startTime, curtime);
    //   console.log(startTime);
    // }
    this.setData({
      selstartTime: "请选择",
      selendTime: "请选择", 
      // startTime: startTime,
      endTime: ["请先选择起始时间"],
      activedateid: e.currentTarget.id
    });
  },
  fun_date: function(a){
    var date1 = new Date();
    var date2 = new Date(date1);
    date2.setDate(date1.getDate()+a);
    var mon = date2.getMonth() + 1;
    var day = date2.getDate();
    var time =(mon < 10 ? ('0' + mon) : mon) + "-" + (day < 10 ? ('0' + day) : day);
    if(a === 0){
      // time += '\n(今)';
    }
    else if (a === 1) {
      // time += '\n(明)';
    }
    return time;
  },
  getTimeArray:function(arr,obj){
    var index = -1;
    for (var i = 0; i < arr.length; i++) {
      if (arr[i] > obj) {
        index = i;
        break;
      }
    }
    if (index != -1) {
      arr = arr.slice(index);
    }
    else {
      arr = ["今天无有效时间",];
    }
    return arr;
  },

  modalHideCancle: function () {
    this.setData({
      modalContent: '',
      modalHidden: true
    });
    console.log(1);
  },
  handleTouchStart:function(e){
    this.data.startY = e.touches[0].clientY;
    // console.log();
  },
  handleTouchMove:function(e){
    const moveY = e.touches[0].clientY;
    const direction = moveY > this.data.startY ? 'up' : 'down';
    console.log(`用户正在向${direction}滑动${moveY}`);
  },
  handleTouchEnd:function(e){
    const moveY = e.changedTouches[0].clientY;
    const direction = moveY > this.data.startY ? 'up' : 'down';
    console.log(`用户向${direction}滑动结束${moveY}`);
  },
  subscribeClick:function(e){
    var Select = (e.target.id).split('-');
    console.log(this.data.date[parseInt(Select[1])+1])
    this.setData({
      timedateid:e.target.id,
      selectDay:this.data.date[parseInt(Select[1])+1].datestr,
      selectStartTime:this.data.startTime[parseInt(Select[0])],
      selectEndTime:this.data.startTime[parseInt(Select[0]) + 1],
    })
  },
  appointtap:function(){
    if (this.data.selectTime == "" || this.data.selectDay == ""){
      wx.showToast({
        title: '请先选择正确的预约时段',
        image: '../../images/popup-close.png'
      });
      return;
    }
    const curselDay = this.data.date[this.data.activedateid].datestr;
    this.setData({
      modalContent: '请确认您预定的教练信息\r\n教练: ' + this.data.coach.coach_name + '\r\n预约日期: ' + this.data.selectDay +'\r\n预约时间: ' + this.data.selectStartTime + '--' + this.data.selectEndTime + '\r\n请检查无误后点击确认',
      modalHidden: false
    });
  },
  modalHide: function () {
    this.setData({
      modalContent: '',
      modalHidden: true
    });
    // console.log(wx.getStorageSync('userInfo').u_id);
    req.post('/user_appointment_course/index', {user_id:wx.getStorageSync('userInfo').u_id,selectDay:this.data.selectDay,selectStartTime:this.data.selectStartTime,selectEndTime:this.data.selectEndTime,class_id:this.data.class_id}, 1).then(res => {
      console.log(res.data);

    });
  },
  courseClick:function(e){
    let course = this.data.course;
    var that = this;
    course.forEach(item => {
      if(item.class_id == e.currentTarget.id){
        that.setData({
            start_date:item.start_date,
            end_date:item.end_date,
            start_time:item.start_time,
            end_time:item.end_time,
            duration:item.duration,
            class_id:item.class_id
          })
          var date = [{id:-1,'datestr':'时间日期'}];
          for(var i = 0;i<7;i++){
            var onedate = {};
            onedate.id = i;
            onedate.datestr = that.setTime(i,item.start_date);
            date.push(onedate);
          }
          var starttimedatetime = (item.start_time).split(':');
          var endtimedatetime = (item.end_time).split(':');
          // const hours = datetime.getHours();
          // const minutes = datetime.getMinutes();
          // const curtime = (hours < 10 ? ('0' + hours) : hours) + ":" + (minutes < 10 ? ('0' + minutes) : minutes);
          // var startTime = that.data.startTime;
          var hours = 0;
          var startTime = [];
          var broken = parseInt(((parseInt(endtimedatetime[0]) - parseInt(starttimedatetime[0]))*60)/item.duration)
          for(var i = 0;i<=broken;i++){
            var hoursDate = parseInt((item.duration*i)/60);
            var minutesDate = (item.duration*i) - 60*hoursDate;
            hours = parseInt(starttimedatetime[0])+hoursDate;
            startTime[i] = (hours < 10 ? ('0' + hours) : hours)+':'+(minutesDate < 10 ? ('0' + minutesDate) : minutesDate);
          }
          console.log(startTime);
          
          that.setData({
            date:date,
            startTime: startTime, 
            courseId : e.currentTarget.id
          })
          // console.log(1);
      }
    });
  },
  setTime:function(a,time){
    var date1 = new Date(time);
    // console.log(date1); 
    var date2 = new Date(date1);
    date2.setDate(date1.getDate()+a);
    var mon = date2.getMonth() + 1;
    var day = date2.getDate();
    var time =(mon < 10 ? ('0' + mon) : mon) + "-" + (day < 10 ? ('0' + day) : day);
    return time;
    // console.log(time);
    // return time;
  }
})